var DigitialUniversity = new function() {
	
	/* RESET HEADERS */
	this.resetHeaderToggles = function() {		
	
		// Hide all open toggles
		$('.pBxToggle').hide();
		
	};
		
	this.toEntity = function(str) {
		var rtr = '';
		for(i=0; i < str.length; i++) {
			if(str.charCodeAt(i)>127) {
				rtr += '&#' + str.charCodeAt(i) + ';';
			} else{
				rtr += str.charAt(i);
			}
		}
		return rtr;
	};
	
	this.addNewResource = function() {
		
		// Are we adding a resource?
		if($('#addNewResource').length == 0) {
			return;
		}
		
		// Select change
		$('#type').change(function(e) {
			if($(this).val() == 'webpage') {
				$('#addNewResource .fileField').addClass('hidden');
				$('#addNewResource .webPageField').removeClass('hidden');					
			} else {
				$('#addNewResource .fileField').removeClass('hidden');
				$('#addNewResource .webPageField').addClass('hidden');	
			}
		});
		
	};
	
	this.addComment = function() {
			
		var textarea = $('#commentsContainer textarea[name="commentEntryInput"]');	
		var type = textarea.data('type');
		var ID = String(textarea.attr('data-' + type));
		var value = this.toEntity(textarea.val());
			
		// Load page content
		$.ajax({
			data: {
				'type': type,
				'ID': ID,
				'value': value
			},
			success: function(mainText) {
				
				if(mainText.error == false) {
					
					// No comments text
					if($('#commentsContainer #noComments').length != 0) {
						$('#commentsContainer #noComments').remove();
					}
					
					// Add comment to top
					$('#commentsContainer').prepend(mainText.comment);	
					
					// Reset value
					textarea.val('');
					
				} else {					
					console.log('An error occurred processing this request.');					
				}
					
			},
			error: function() {				
				console.log('An error occurred processing this request.');
			},
			dataType: 'json',
			url: rooturl + "ajax/addComment/",
			type: 'POST'
		});
		
	};
	
	this.loadTextarea = function() {
		
		// Any comment container?
		if($('#commentsContainer').length == 0) {
			return;
		}
		
		// Local copy
		var self = this;
		
		// Textarea 1-click activation
		$('#commentsContainer textarea[name="commentEntryInput"]').one('click', function(event) {
			$(this).keydown(function(e) {
				var keyCode = (e.keyCode ? e.keyCode : e.which);
				if((keyCode == 13 || keyCode == 10) && !e.shiftKey) {
					if(!e.ctrlKey) {
						self.addComment(); 
					}
					e.preventDefault();
				}
			});	
		});    
		
	};
		
	this.loadRatingSubmit = function() {
		
		// Do we have a rating form?
		if($('#ratingSubmit').length == 0) {
			return;
		}
		
		// Disabled or active?		
		if($('#ratingSubmit').data('disabled') == true) {
			return;	
		}
		
		// Click events
		$('#ratingSubmit .lightStar, #ratingSubmit .ratingButton').click(function(event) {
			
			var type = $('#ratingSubmit').data('type');
			var ID = String($('#ratingSubmit').attr('data-' + type));
			var rating = $(this).data('rating');
			
			// Load page content
			$.ajax({
				data: {
					'type': type,
					'ID': ID,
					'rating': rating
				},
				success: function(mainText) {
					
					// Safety method - already voted
					if(!mainText.userHasVoted) {
						
						// New width
						$('#ratingSubmit .darkStar').width(mainText.width);
						$('#ratingSubmit .percentage').html(mainText.percentage);
						$('#ratingSubmit .voteButtonContainer').remove();
						
						// Votes counter
						if($('#ratingSubmit h3.votesCast').length == 0) {
							$('#ratingSubmit .rating').after('<h3 class="votesCast">' + mainText.voteCast + '</h3>');
						} else {
							$('#ratingSubmit h3.votesCast').html(mainText.voteCast);	
						}
						
					}
					
				},
				error: function() {				
					console.log('An error occurred processing this request.');
				},
				dataType: 'json',
				url: rooturl + "ajax/rating/",
				type: 'POST'
			});
			
		});
		
	};
	
	this.loadTwitterFeed = function() {
		
		// Found twitter feed?
		if($('#twitterFeed').length == 0) {
			return;
		}
		
		// Load page content
		$.ajax({
			success: function(mainText) {
				var showText = '';
				for(i = 0; i < mainText.length; i++) {
					showText += '<div class="clearfix">' + mainText[i].title + '<div class="time">' + mainText[i].linkTime + '</div></div>';		
				}
				$('#twitterFeed').html(showText);
			},
			error: function() {				
				showNotification('An error occurred processing this request.');
			},
			dataType: 'json',
			url: rooturl + "ajax/getTwitterFeed/",
			type: 'GET'
		});
	
	};
	
	this.loadTabberMenu = function() {
		
		$('nav.pageTab a').click(function(event) {
			
			if($(this).data('tab') != 'notabber') {
			
				// Prevent default
				event.preventDefault();
						
				// Remove focus/tab
				$('nav.pageTab a').removeClass('focus');
				$('.dataTab').hide();
				
				// Add focus to selected
				$(this).addClass('focus');			
				$('#tab_' + $(this).data('tab')).show();
			
			}
			
		});
		
	};
	
	this.createFileFilter = function() {
		
		// Nothing to do
		if($('#tab_resources #fileFilter').length == 0) {
			return;
		}
		
		// Assign click event
		$('#tab_resources #fileFilter a').click(function(event) {
			
			// Prevent default
			event.preventDefault();
			
			var type = $(this).data('type');
			
			// Show all
			if(type == 'all') {
				
				// Hide all
				$('#tab_resources .document').show();
				
			} else {
			
				// Hide all
				$('#tab_resources .document').hide();
				
				// Show only specified type
				$('#tab_resources .' + $(this).data('type')).show();
			
			}
			
			// Count - none found
			if($('#tab_resources .document:visible').length == 0) {
			
				$('#tab_resources #noResources').removeClass('hidden');
					
			} else {
			
				$('#tab_resources #noResources').addClass('hidden');
				
			}
			
		});
		
	};
	
	this.autoSearch = function() {
				
		var minSearchLength = 4;
		
		// Keyup event
		$("#searchBox").keyup(function() {
			
			// Store variables
			var self = this, value = $(this).val();
	
			// Input is long enough?
			if(value.length >= minSearchLength) {
				
				// Make AJAX request
				$.ajax({
					type: "POST",
					url: rooturl + "ajax/search/",
					data: 'keyword=' + value,
					dataType: "json",
					success: function(mainText){
						$('#searchResults').html(mainText.results).fadeIn();
					}
				});
				
			}
			
		});
		
	};
			
	/*
	 * initialise: Declare page initialise scripts
	*/
	this.initialise = function() {
	
		// Load tab menus
		this.loadTabberMenu();
		this.createFileFilter();
		
		// Load ratings
		this.loadRatingSubmit();
		
		// Load textarea
		this.loadTextarea();
		
		// Search box
		this.autoSearch();
	
		// Placeholders
		$('input[placeholder] ,textarea[placeholder]').placeholder();
	
		var self = this;
			
		$('body, html').click(function(event) {
				
			// Hide all open toggles
			self.resetHeaderToggles();
				
		});
		
		$('.pBxToggle').click(function(event) {
		
			event.stopPropagation();
			
		});
		
		// Popup toggles
		$('a[rel="toggleDialog"]').click(function(event) {
						
			// Stop propagation of all other events			
			event.stopPropagation();
			
			// Get extra data
			var dataToggle = $(this).attr('data-toggle');
			var toggleElement = '#cBxDialog-' + dataToggle;
			
			// Mark as read?
			if(dataToggle == 'notifications') {
				
				if($(this).hasClass('newNotifications')) {
						
					var element = $(this);
									
					// Load page content
					$.ajax({
						data: 'action=read',
						success: function(mainText) {		
							element.removeClass('newNotifications');							
						},
						error: function() {				
							console.log('An error occurred processing this request.');
						},
						dataType: 'json',
						url: rooturl + "ajax/notifications/",
						type: 'POST'
					});
				
				}
				
			}
			
			// Is currently visible?
			var isVisible = $(toggleElement).is(":visible");
						
			// Close all open toggles
			self.resetHeaderToggles();
			
			// Toggle dialog
			if(!isVisible) {
			
				// Fade element in
				$(toggleElement).fadeToggle(250);
				
			}
			
			// Prevent default
			event.preventDefault();
			
		});		
						
	};	
		
}

// Initialise
$(document).ready(function() {
	DigitialUniversity.initialise();
	DigitialUniversity.loadTwitterFeed();
});